<template>
  <div>
    <van-cell-group inset>
      <van-field
        v-model:value="createTeamForm.name"
        name="pattern"
        label="队伍名称:"
        placeholder="队伍名称长度不能超过15"
        required
        @change="changeInput($event, 'name')"
        
        :error-message="[validateErr.name===true?'请检查队伍名称':'']"
      />
      <van-cell title="队伍头像">
        <van-image
        v-if="tempFile"
            width="50px"
            height="50px"
            fit="cover"
            :src="tempFile"
            @click="selectImg"
          />
      </van-cell>
      <van-field
        v-model:value="createTeamForm.description"
        rows="2"
        autosize
        label="队伍描述:"
        type="textarea"
        maxlength="500"
        placeholder="请输入队伍描述"
        show-word-limit
        required
        :error-message="[validateErr.description===true?'队伍不能为空':'']"
        @change="changeInput($event, 'description')"
        
      />

      <van-field
        name="stepper"
        label="最大人数"
       
      >
        <template #input>
          <van-stepper :value="createTeamForm.maxNum" max="10" min="3" @change="changeInput($event, 'maxNum')" />
        </template>
      </van-field>
      <div @click="showPopup">
        <van-field
          v-model:value="createTeamForm.expireTime"
          readonly
          label="过期时间:"
          type="text"
          is-link
          placeholder="请选择过期时间"
          required
          :rules="[{ validator: validatorMessage }]"
          :error-message="[validateErr.expireTime===true?'过期时间不能为空':'']"
        />
      </div>

      <van-field name="radio" label="队伍状态">
        <template #input>
          <van-radio-group
            :value="createTeamForm.status"
            direction="horizontal"
            @change="changeInput($event, 'status')"
          >
            <van-radio name="0">公开</van-radio>
            <van-radio name="1">私有</van-radio>
            <van-radio name="2">加密</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-if="Number(createTeamForm.status) === 2"
        v-model="createTeamForm.password"
        type="password"
        name="password"
        label="密码"
        :required="[Number(createTeamForm.status) === 2?true:false]"
        placeholder="请输入队伍密码"
        :rules="[{ required: true, message: '请填写密码' }]"
        
        @change="changeInput($event, 'password')"
        :error-message="[validateErr.password===true?'请检查队伍密码':'']"
      />
    </van-cell-group>

    <!-- 时间日期选择 -->
    <van-popup :show="show" position="bottom" custom-style="height: 50%;">
      <van-datetime-picker
        type="datetime"
        :value="currentDate"
        :min-date="minDate"
        :max-date="maxDate"
        @input="onInput"
        @confirm="confirmDate"
        @cancel="closePopup"
      />
    </van-popup>

    <div style="margin: 16px">
      <van-button
        round
        block
        type="primary"
        native-type="submit"
        @click="submitData()"
      >
        提交
      </van-button>
    </div>
  </div>
  <van-notify id="van-notify" />
</template>
<script setup>
import { ref, reactive } from 'vue'
import { parseTime } from '../utils/dateTimeFormat'
import { createTeam } from '../api/team/team'

let dateObj = ref({
  minHour: 10,
  maxHour: 20,
  minDate: new Date().getTime(),
  maxDate: new Date(2099, 12, 31).getTime(),
  currentDate: new Date().getTime(),
})
let createTeamForm = ref({
  name: '',
  maxNum: 3,
  description: '',
  expireTime: '',
  password: '',
  status: '0',
})
const i=0

let show = ref(false) //展示时间选择器
let validateErr=ref({
  name:false,
  description:false,
  expireTime:false,
  password:false
})
const minHour = ref(10)
const maxHour = ref(20)
const minDate = ref(new Date().getTime())
const maxDate = ref(new Date(2099, 12, 31).getTime())
const currentDate = ref(new Date().getTime())
const tempFile=ref("https://oooo111.oss-cn-hangzhou.aliyuncs.com/uploadTips.jpg")
//选择时间后确认
const onConfirmForTeam = () => {
  // showToast(`${currentDate.value.join('/')} ${currentTime.value.join(':')}`)
  createTeamForm.value.expireTime = `${currentDate.value.join(
    '-'
  )} ${currentTime.value.join(':')}`
  show.value = false
}
//选择时间取消
const onCancelForTime = () => {
  // showToast('cancel')
  show.value = false
}
// 校验函数返回 true 表示校验通过，false 表示不通过
const validator = (val) => /1\d{10}/.test(val)

// 校验函数可以直接返回一段错误提示
const validatorMessage = (val) => {
  if (val === null || val === '') {
    return '不能为空'
  }
  return true
}
console.log('时间戳：', new Date().getTime())

// 校验函数可以返回 Promise，实现异步校验
const asyncValidator = (val) =>
  new Promise((resolve) => {
    showLoadingToast('验证中...')

    setTimeout(() => {
      closeToast()
      resolve(val === '1234')
    }, 1000)
  })

const onFailed = (errorInfo) => {
  console.log('failed', errorInfo)
}
//提交数据
const submitData = async () => {
  const isFormValid = validateVal();  // 调用校验方法

if (!isFormValid) {
  uni.showToast({ title: '请检查表单输入', icon: 'none' });
  return;
}
  await upload()
  const res = await createTeam(createTeamForm.value)
  console.log(res)
  uni.showToast({
    title: '创建成功',
    icon: 'success',
    
    // navigateBack
  })
  setTimeout(()=>{
    uni.navigateBack({
    delta: 1,
  })
  },1500)
  
}
const showPopup = () => {
  show.value = true
}
//时间选择器
const onInput = ($event) => {
  console.log(dateObj.value)

  dateObj.value.currentDate = $event.detail
}
//选中时间确定
const confirmDate = ($event) => {
  console.log($event)
  const seletedTime = parseTime($event.detail, '{y}-{m}-{d} {h}:{i}:{s}')
  console.log(seletedTime)
  createTeamForm.value.expireTime = seletedTime
  // currentDate.value=seletedTime
  show.value = false
}
//关闭弹窗
const closePopup = () => {
  show.value = false
}
//
const changeInput = (e, keyWord) => {
  let map = new Map([
    [
      'name',
      (detail) => {
        createTeamForm.value.name = detail
      },
    ],
    [
      'description',
      (detail) => {
        createTeamForm.value.description = detail
      },
    ],
    [
      'maxNum',
      (detail) => {
        createTeamForm.value.maxNum = detail
      },
    ],
    [
      'password',
      (detail) => {
        createTeamForm.value.password = detail
      },
    ],
    [
      'status',
      (detail) => {
        createTeamForm.value.status = detail
      },
    ],
  ])
  const handeler = map.get(keyWord)
  if (handeler) {
    handeler(e.detail)
  } else {
    console.log('没找到该函数')
  }
}
//数据校验
const validateVal=(e,keyWord)=>{
  let isValid = true;

  // 使用 Map 来存储表单字段和校验规则
  const validations = new Map([
    ['name', {
      condition: () => createTeamForm.value.name === '' || createTeamForm.value.name.length > 15,
      errorKey: 'name',
      errorMessage: '队伍名称不能为空或超过15字符'
    }],
    ['description', {
      condition: () => createTeamForm.value.description === '',
      errorKey: 'description',
      errorMessage: '队伍描述不能为空'
    }],
    ['expireTime', {
      condition: () => createTeamForm.value.expireTime === '',
      errorKey: 'expireTime',
      errorMessage: '过期时间不能为空'
    }],
    ['password', {
      condition: () => createTeamForm.value.status === '2' && 
                        (createTeamForm.value.password === '' || createTeamForm.value.password.length > 32),
      errorKey: 'password',
      errorMessage: '加密状态下，密码不能为空且不能超过32字符'
    }]
  ]);

  // 遍历 Map 进行校验
  validations.forEach((validation, field) => {
    if (validation.condition()) {
      validateErr.value[validation.errorKey] = true;
      isValid = false;
    } else {
      validateErr.value[validation.errorKey] = false;
    }
  });

  // 返回整体校验结果
  return isValid;

  
}
//选择照片
const selectImg=()=>{
  uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: function (res) {
          console.log(res);
          
            console.log(JSON.stringify(res.tempFilePaths[0]));
            tempFile.value=res.tempFiles[0].path
            console.log(tempFile.value);
            
        }
    });
}
//上传
const upload=()=>{
  return new Promise((resolve,reject)=>{
    uni.uploadFile({
                url:'https://www.pickteams.cn/api/team/upload',
                filePath:tempFile.value,
                name: 'file',
                header:{
                    "Authorization":uni.getStorageSync('Authorization'),
                    "content-type":"utf-8"
                },
                success: (uploadFileRes) => {
                    console.log(uploadFileRes.data);
                    const result=JSON.parse(uploadFileRes.data)
                    if(result.code===0){
                      createTeamForm.value.url=result.data
                        resolve(result)
                    }else{
                        uni.showToast({
                            title:'上传失败',
                            icon:'fail'
                        })
                        reject("上传失败")
                    }
                }
            })
  })
}
</script>
<style scoped></style>
